<template>
	<el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable width="600">
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="120px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="24" class="mb20">
					<el-form-item label="设备类型" prop="deviceTypeId">
						<el-select v-model="form.deviceTypeId" filterable placeholder="请选择设备类型" @change="getModelList">
							<el-option v-for="item in deviceTypeList" :key="item.id" :value="item.id" :label="item.typeName" :disabled="item.state === 20" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item label="设备型号" prop="deviceModelId">
						<el-select v-model="form.deviceModelId" filterable placeholder="请选择设备型号" @change="handleModelChange">
							<el-option
								v-for="item in deviceModelList"
								:key="item.id"
								:value="item.id"
								:label="item.deviceModelName"
								:disabled="item.state === 20"
							/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="事件名称" prop="eventTypeId">
						<el-select v-model="form.eventTypeId" filterable placeholder="请选择事件名称">
							<el-option v-for="item in eventTypeList" :key="item.id" :value="item.id" :label="item.eventTypeName" :disabled="item.state === 10" />
						</el-select>
					</el-form-item>
				</el-col>
				<!-- <el-col :span="24" class="mb20">
					<el-form-item label="检测类型" prop="detectionId">
						<el-select v-model="form.detectionId" filterable placeholder="请选择检测类型" @change="handleChangeDetectionType">
							<el-option
								v-for="item in detectionTypeList"
								:key="item.id"
								:value="item.id"
								:label="item.detectionTypeName"
								:disabled="item.state === 10"
							/>
						</el-select>
					</el-form-item>
				</el-col> -->
				<el-col :span="24" class="mb20">
					<el-form-item label="传感器" prop="sensorId">
						<el-select v-model="form.sensorId" filterable placeholder="请选择传感器" @change="handleChangesensorType">
							<el-option v-for="item in sensorTypeList" :key="item.id" :value="item.id" :label="item.sensorTypeName" :disabled="item.state === 10" />
						</el-select>
					</el-form-item>
				</el-col>
				<div :gutter="24" v-for="(item, index) in form.alarmRulesDetailsList" :key="item.id" class="w-full">
					<el-col :span="24" class="mb20">
						<el-form-item
							label="运算符"
							:prop="'alarmRulesDetailsList.' + index + '.operator'"
							:rules="{
								required: true,
								message: '请选择运算符',
								trigger: 'change',
							}"
						>
							<div class="flex items-center w-full">
								<el-select v-model="item.operator" placeholder="请选择运算符">
									<el-option v-for="item in operatorList" :key="item.id" :value="item.value" :label="item.label" />
								</el-select>
								<el-button icon="delete" class="ml-2" link type="danger" v-if="index !== 0" @click="handleDelete(index)"></el-button>
							</div>
						</el-form-item>
					</el-col>
					<el-col :span="24" class="mb20">
						<el-form-item
							label="阈值"
							:prop="'alarmRulesDetailsList.' + index + '.threshold'"
							:rules="{
								required: true,
								message: '请输入阈值',
								trigger: 'blur',
							}"
						>
							<el-input-number :value-on-clear="0" :controls="false" v-model="item.threshold" placeholder="请输入阈值" />
						</el-form-item>
					</el-col>
					<el-col :span="24" class="mb20" v-if="index !== form.alarmRulesDetailsList.length - 1">
						<el-form-item
							label="逻辑运算符"
							:prop="'alarmRulesDetailsList.' + index + '.logicalOperator'"
							:rules="{
								required: true,
								message: '请选择运算符',
								trigger: 'change',
							}"
						>
							<el-select v-model="item.logicalOperator" placeholder="请选择运算符">
								<el-option v-for="item in logicalOperatorList" :key="item.id" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
				</div>
				<el-col :span="24" class="mb20" v-show="form.sensorId">
					<el-form-item label="表达式：">
						<div class="w-full p-4 border-[1px] border-info rounded-[4px] overflow-x-auto flex">
							<div v-for="(item, index) in form.alarmRulesDetailsList" :key="item.id" class="flex items-center flex-nowrap">
								<!-- <span class="text-info whitespace-nowrap">{{ form.detectionTypeName }}</span> -->
								<span class="text-info whitespace-nowrap">({{ form.sensorTypeName }})</span>
								<span class="mx-1 text-[#000] font-semibold whitespace-nowrap">{{ item.operator }}</span>
								<span class="whitespace-nowrap">{{ item.threshold }}</span>
								<span v-if="index !== form.alarmRulesDetailsList.length - 1" class="px-2 font-semibold text-warning whitespace-nowrap">{{
									item.logicalOperator
								}}</span>
							</div>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20">
					<div class="flex justify-end w-full">
						<el-button type="success" size="small" icon="Plus" @click="handleAdd">添加计算规则</el-button>
					</div>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="通知方式">
						<el-checkbox v-model="form.smsAlarm" label="短信" :true-label="20" :false-label="10" border />
						<el-checkbox v-model="form.telephoneAlarm" label="电话" :true-label="20" :false-label="10" border />
						<el-checkbox v-model="form.officialAccountAlarm" label="公众号" :true-label="20" :false-label="10" border />
					</el-form-item>
				</el-col>
				<el-col :span="24" class="mb20" v-if="!form.id">
					<el-form-item label="状态" prop="state">
						<el-radio-group v-model="form.state">
							<el-radio :label="20">启用</el-radio>
							<el-radio :label="10">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item label="备注" prop="remarks">
						<el-input type="textarea" resize="none" show-word-limit :rows="5" v-model="form.remarks" placeholder="请输入备注" maxlength="100" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="AlarmRulesDialog">
import { useMessage } from '/@/hooks/message';
import { getObj, addObj, putObj } from '/@/api/alarm/alarmRules';
import { fetchListAll } from '/@/api/platform/basicDeviceType';
import { fetchListAll as fetchAllModelList } from '/@/api/platform/basicDeviceModel';
import { fetchListAll as fetchEventTypeList } from '/@/api/alarm/alarmEventType';
import { fetchListAll as fetchSensorTypeList } from '/@/api/alarm/basicSensor';
import { rule } from '/@/utils/validate';
import { operatorList, logicalOperatorList } from './data';
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const deviceTypeList: any = ref([]);
const deviceModelList: any = ref([]);
const eventTypeList: any = ref([]);
const sensorTypeList: any = ref([]);
// 定义字典

// 提交表单数据
const form = reactive({
	id: '',
	remarks: '',
	state: 20,
	eventTypeId: '',
	eventTypeCode: '',
	eventTypeName: '',
	deviceTypeId: '',
	deviceTypeName: '',
	deviceModelId: '',
	deviceModelName: '',
	detectionId: '',
	detectionTypeCode: '',
	detectionTypeName: '',
	sensorId: '',
	sensorTypeCode: '',
	sensorTypeName: '',
	expression: '',
	smsAlarm: 20,
	officialAccountAlarm: 20,
	telephoneAlarm: 20,
	alarmTypeCode: '',
	alarmTypeName: '',
	alarmTypeId: '',
	operator: '',
	alarmRulesDetailsList: [
		{
			operator: null,
			threshold: null,
			logicalOperator: null,
			id: new Date().getTime(),
		},
	],
});
const expressionItem = {
	operator: null,
	threshold: null,
	logicalOperator: null,
	id: new Date().getTime(),
};
// 定义校验规则
const dataRules = ref({
	deviceTypeId: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
	deviceModelId: [{ required: true, message: '请选择设备型号', trigger: 'change' }],
	eventTypeId: [{ required: true, message: '请选择事件名称', trigger: 'change' }],
	// detectionId: [{ required: true, message: '请选择检测类型', trigger: 'change' }],
	sensorId: [{ required: true, message: '请选择传感器', trigger: 'change' }],
});
// 表达式数据
// 打开弹窗
const openDialog = (id: string) => {
	visible.value = true;
	form.id = '';
	form.alarmRulesDetailsList = [expressionItem];
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});

	// 获取alarmRules信息
	if (id) {
		form.id = id;
		getalarmRulesData(id);
	}
	getDeviceTypes();
	// getDetectionList();
	// getSensorTypeList();
	getSensorTypeList();
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		const deviceModelItem = deviceModelList.value.find((d: { id: string }) => d.id === form.deviceModelId);
		form.deviceModelName = deviceModelItem.deviceModelName;
		const deviceTypeItem = deviceTypeList.value.find((d: { id: string }) => d.id === form.deviceTypeId);
		form.deviceTypeName = deviceTypeItem.typeName;
		const sensorItem = sensorTypeList.value.find((d: { id: string }) => d.id === form.sensorId);
		form.sensorTypeCode = sensorItem.sensorTypeCode;
		form.sensorTypeName = sensorItem.sensorTypeName;
		const eventItem = eventTypeList.value.find((d: { id: string }) => d.id === form.eventTypeId);
		let expression: string = '';
		for (let i = 0; i < form.alarmRulesDetailsList.length; i++) {
			const item = form.alarmRulesDetailsList[i];
			expression += form.sensorTypeName + item.operator + item.threshold + (i === form.alarmRulesDetailsList.length - 1 ? '' : item.logicalOperator);
		}
		form.expression = expression;
		form.eventTypeCode = eventItem.eventTypeCode;
		form.eventTypeName = eventItem.eventTypeName;
		form.alarmTypeCode = eventItem.alarmTypeCode;
		form.alarmTypeName = eventItem.alarmTypeName;
		form.alarmTypeId = eventItem.alarmTypeId;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 初始化表单数据
const getalarmRulesData = (id: string) => {
	// 获取数据
	loading.value = true;
	getObj(id)
		.then((res: any) => {
			getModelList(res.data.deviceTypeId);
			getEventTypeList(res.data.deviceTypeId, res.data.deviceModelId);
			Object.assign(form, res.data);
		})
		.finally(() => {
			loading.value = false;
		});
};

// 获取设备数据
const getDeviceTypes = () => {
	fetchListAll({ state: 10 }).then((res) => {
		deviceTypeList.value = res.data;
	});
};
// 查询设备型号
const getModelList = (deviceTypeId: string) => {
	form.deviceModelId && (form.deviceModelId = '');
	form.deviceModelId && (form.eventTypeId = '');
	fetchAllModelList({ deviceTypeId, state: 10 }).then((res) => {
		deviceModelList.value = res.data;
	});
};
const getSensorTypeList = () => {
	fetchSensorTypeList({ state: 20 }).then((res) => {
		sensorTypeList.value = res.data;
	});
};
const getEventTypeList = (deviceTypeId: string, deviceModelId: string) => {
	fetchEventTypeList({ deviceModelId: deviceModelId, deviceTypeId: deviceTypeId, alarmTypeCode: 'RULES_ALARM', state: 20 }).then((res) => {
		eventTypeList.value = res.data;
	});
};
const handleModelChange = () => {
	form.eventTypeId = '';
	getEventTypeList(form.deviceTypeId, form.deviceModelId);
};
const handleAdd = () => {
	form.alarmRulesDetailsList.push({
		operator: null,
		threshold: null,
		logicalOperator: null,
		id: new Date().getTime(),
	});
};
const handleChangesensorType = (e: string) => {
	const sensor = sensorTypeList.value.find((d: { id: string }) => d.id === e);
	if (sensor) {
		form.sensorTypeCode = sensor.sensorTypeCode;
		form.sensorTypeName = sensor.sensorTypeName;
	}
};
// 删除规则
const handleDelete = (index: number) => {
	form.alarmRulesDetailsList.splice(index, 1);
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>
